﻿using MSAcademic.v2.Database;
using MSAcademic.v2.Infrastructure.Article;
using MSAcademic.v2.Infrastructure.Article.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MSAcademic.v2.Infrastructure.Search.Impl
{
    public class SearchQueriesImpl : ISearchQueries
    {
        public IEnumerable<IArticle> SearchAllArticles(string searchItem)
        {
            using (var db = new MSAcademicDatabaseContainer())
            {
                if (string.IsNullOrWhiteSpace(searchItem)) { return new List<IArticle>(); }
                var searchTokens = searchItem.ToLower().Split(' ');

                var articles = db.Articles.
                    Where(x =>
                            (x.Title.ToLower().Contains(searchItem.ToLower())

                            || (x.User.FirstName + " "  + x.User.LastName).ToLower().Contains(searchItem)

                            || x.Tags.Where(t => searchTokens.Contains(t.Name.ToLower())).Any())

                            && x.PublishedOn.HasValue
                            && !x.IsHidden
                         ).
                    Select(x => new ArticleImpl
                    {
                        Title = x.Title,
                        Id = x.Id,
                        ShortText = x.ShortText,
                        LongText = x.LongText,
                        IsHidden = x.IsHidden,
                        CreatedOn = x.CreatedOn,
                        PublishedOn = x.PublishedOn,
                        PictureUrlBig = x.PictureUrlBig,
                        PictureUrlNormal = x.PictueUrlNormal,
                        PictureUrlThumbnail = x.PictureUrlThumbnail
                    }).OrderByDescending(x => x.PublishedOn.Value).ToList();

                return articles;
            }
        }
    }
}
